package sync.copy;

import java.io.UnsupportedEncodingException;
import java.net.URL;

import net.HttpPostConnector;
import net.HttpRequestFacade;

import org.json.simple.JSONObject;

public class BoxInfoSynchronizer {
	private static final String BOX_VERSION_TOKEN = "version";
	private static final String OPERATING_SYSTEM_NAME_TOKEN = "os";
	private static final String OPERATING_SYSTEM_VERSION_TOKEN = "osversion";
	private static final String HARDWARE_INFO = "hwinfo";
	private static final String TEAMVIEWER_ID = "teamviewer_id";
	private BoxSystemInfo systemInfo;

	public BoxInfoSynchronizer(BoxSystemInfo systemInfo) {
		this.systemInfo = systemInfo;
	}

	public void sendBoxInfo() {
		URL webtoolURL = HttpRequestFacade.getWebtoolURL();
		if (webtoolURL == null) {
			return;
		}
		String requestString;
		requestString = getRequestString();
		HttpPostConnector connector = new HttpPostConnector(webtoolURL, HttpPostConnector.getBoxToken() + "&"
				+ "reqtype=playerInfo&" + requestString);
		connector.post();
	}

	public String getRequestString() {
		StringBuilder sb = new StringBuilder();
		sb.append(BOX_VERSION_TOKEN);
		sb.append('=');
		sb.append(encode("" + systemInfo.getBoxVersion()));
		sb.append('&');
		sb.append(OPERATING_SYSTEM_NAME_TOKEN);
		sb.append('=');
		sb.append(encode(systemInfo.getOperatingSystemName()));
		sb.append('&');
		sb.append(OPERATING_SYSTEM_VERSION_TOKEN);
		sb.append('=');
		sb.append(encode(systemInfo.getOperatingSystemVersion()));
		sb.append(TEAMVIEWER_ID);
		sb.append('=');
		sb.append(encode("" + systemInfo.getTeamviewerID()));
		sb.append('&');
		sb.append(HARDWARE_INFO);
		sb.append('=');
		
		JSONObject obj = new JSONObject();
		obj.put("hwinfo", systemInfo.getHardwareInformation());
		sb.append(encode(obj.toJSONString()));

		return sb.toString();
	}

	private String encode(String str) {
		try {
			return java.net.URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return str;
		}
	}
}
